import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'dart:io';

Effect<UserInfoState> buildEffect() {
  return combineEffects(<Object, Effect<UserInfoState>>{
    UserInfoAction.onTap: _onTap,
    UserInfoAction.onSubmit: _onSubmit,
  });
}

void _onTap(Action action, Context<UserInfoState> ctx) async {
  if (action.payload == 0) {
    File imgFile =
        await CommonUtils.showImagePicker(ctx.context, cropImg: true);
    if (imgFile == null) {
      return;
    }
    ctx.state.selectImage = imgFile;
    ctx.dispatch(UserInfoActionCreator.onAction());
  }
}

void _onSubmit(Action action, Context<UserInfoState> ctx) async {
  if (ctx.state.selectImage != null) {
    CommonUtils.showWaitLoading(ctx.context);
    ResultData res = await CommonNetWork.uploadImg(ctx.state.selectImage);
    print(res);
    if (res.success) {
      ctx.state.userInfo.headimg =
          CommonUtils.checkNullToString(res.data);
      GlobalStore.store
          .dispatch(GlobalActionCreator.onUserLogin(ctx.state.userInfo));
      ResultData upRes;
      if (GlobalStore.store.getState().userInfo.isGsUser) {
        upRes =
        await CommonNetWork.updateUserHeader(ctx.state.userInfo.headimg);
      } else {
        upRes = await CommonNetWork.staffUpdateUserHeader(
            ctx.state.userInfo.headimg);
      }
      Navigator.pop(ctx.context);
      if (upRes.success) {
        await CommonUtils.showAlertView(ctx.context, '修改成功');
        Navigator.pop(ctx.context);
      }
      else{
        CommonUtils.showErrorInfo(ctx.context, upRes.desc);
      }

      return;
    } else {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
    // if (res.se) {

    //   if (upRes.success) {
    //     ctx.state.userInfo.headimg = res;

    //     await CommonUtils.showAlertView(ctx.context, '修改成功');
    //     Navigator.pop(ctx.context);
    //     return;
    //   }
    // }
    // Navigator.pop(ctx.context);
  } else
    Navigator.pop(ctx.context);
}
